<script setup>
import { ref } from 'vue'
import {
  deleteQuestion,
  getQuestionUserInfoById,
  pageQueryQuestion
} from '@/api/question.js'
import { Message } from '@arco-design/web-vue'
import router from '@/router/index.js'
import MdViewer from '@/components/MdViewer.vue'

const pageForm = ref({
  id: '',
  title: '',
  tags: [],
  userId: '',
  beginTime: '',
  endTime: '',
  currentPage: 1,
  pageSize: 10
})
const pageFormRef = ref()
const total = ref(0)
const createTime = ref()
const tableLoading = ref(false)
const tableData = ref([])

const columns = [
  {
    title: '标题',
    dataIndex: 'title',
    ellipsis: true,
    tooltip: true,
    width: 180
  },
  {
    title: '标签列表',
    dataIndex: 'tags',
    ellipsis: true,
    tooltip: true,
    width: 220,
    slotName: 'tagsSlot'
  },
  {
    title: '提交',
    dataIndex: 'submitNum',
    ellipsis: true,
    tooltip: true,
    slotName: 'submitNumSlot',
    width: 80
  },
  {
    title: '通过',
    dataIndex: 'acceptedNum',
    ellipsis: true,
    tooltip: true,
    slotName: 'acceptedNumSlot',
    width: 80
  },
  {
    title: '创建用户',
    dataIndex: 'userId',
    ellipsis: true,
    tooltip: true,
    width: 190
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    width: 180
  },
  {
    title: '更新时间',
    dataIndex: 'updateTime',
    width: 180
  },
  {
    title: '操作',
    align: 'center',
    dataIndex: 'action',
    slotName: 'optional'
  }
]


const selectedKeys = ref([])
const rowSelection = ref({
  type: 'checkbox',
  showCheckedAll: true,
  onlyCurrent: false
})

// 重置查询表单
const resetPageForm = () => {
  pageFormRef.value.resetFields()
  createTime.value = ''
}

// 分页处理
const pageChange = (currentPage) => {
  pageForm.value.currentPage = currentPage
  submitPageForm()
}

const pageSizeChange = (pageSize) => {
  pageForm.value.pageSize = pageSize
  submitPageForm()
}

// 查询题目
const submitPageForm = (flag) => {
  if (flag === 1) {
    pageForm.value.currentPage = 1
  }
  if (createTime.value) {
    function convertToChinaTime(utcTimeString) {
      const utcDate = new Date(utcTimeString)
      utcDate.setHours(utcDate.getHours() + 8)
      return utcDate.toISOString()
    }

    pageForm.value.beginTime = convertToChinaTime(createTime.value[0])
    pageForm.value.endTime = convertToChinaTime(createTime.value[1])
  }
  tableLoading.value = true
  pageQueryQuestion(pageForm.value)
    .then(res => {
      if (res.data.code === 1) {
        tableData.value = res.data.data.records
        total.value = Number(res.data.data.total)
      } else {
        Message.error(res.data.message || '查询题目失败')
      }
    })
    .catch(error => {
      console.error(error)
      Message.error('查询题目失败')
    })
    .finally(() => {
      tableLoading.value = false
    })
}
submitPageForm()

// 新增题目
const handleAdd = () => {
  router.push('/question/add')
}

// 编辑题目
const handleEdit = (record) => {
  router.push(`/question/edit/${record.id}`)
}

// 删除题目
const handleDelete = () => {
  const selectedIds = selectedKeys.value
  if (selectedIds.length === 0) {
    Message.warning('请选择要删除的题目')
    return
  }
  deleteQuestion(selectedIds)
    .then(res => {
      if (res.data.code === 1) {
        Message.success('删除成功')
        submitPageForm()
      } else {
        Message.error(res.data.message || '删除失败')
      }
    })
    .catch(error => {
      console.error(error)
      Message.error('删除失败')
    })
}

const questionDetail = ref({
  id: '',
  title: '',
  content: '',
  tags: [],
  answer: '',
  prompt: '',
  submitNum: 0,
  acceptedNum: 0,
  judgeCase: [],
  judgeConfig: {},
  userId: '',
  nickname: '',
  createTime: '',
  updateTime: ''
});
const detailVisible = ref(false)
// 获取题目详情
const handleViewDetail = (id) => {
  getQuestionUserInfoById(id)
    .then(res => {
      if (res.data.code === 1) {
        questionDetail.value = res.data.data
        questionDetail.value.tags = JSON.parse(res.data.data.tags)
        questionDetail.value.judgeCase = JSON.parse(res.data.data.judgeCase)
        questionDetail.value.judgeConfig = JSON.parse(res.data.data.judgeConfig)
        questionDetail.value.prompt = JSON.parse(res.data.data.prompt)
        detailVisible.value = true
      }
    })
    .catch(error => {
      console.error(error)
    })
}
</script>

<template>
  <div id="question-manager">
    <div class="card">
      <div class="set-container">
        <div class="select-container">
          <a-form :model="pageForm" layout="inline" ref="pageFormRef">
            <a-form-item label="题目id" field="id">
              <a-input v-model="pageForm.id" placeholder="请输入题目id"></a-input>
            </a-form-item>
            <a-form-item label="题目标题" field="title">
              <a-input v-model="pageForm.title" placeholder="请输入题目标题"></a-input>
            </a-form-item>
            <a-form-item label="标签列表" field="tags">
              <a-input-tag v-model="pageForm.tags"
                           placeholder="请输入标签(enter输入)"></a-input-tag>
            </a-form-item>
            <a-form-item label="创建用户" field="userId">
              <a-input v-model="pageForm.userId" placeholder="请输入创建用户id"></a-input>
            </a-form-item>
            <a-form-item label="创建时间" field="beginTime">
              <a-range-picker
                showTime
                v-model="createTime"
                :time-picker-props="{ defaultValue: ['00:00:00', '00:00:00'] }"
                :format="'YYYY-MM-DDTHH:mm:ss'"
                style="width: 380px;"
              />
            </a-form-item>
            <div class="button-container">
              <div class="left">
                <a-form-item>
                  <a-button type="primary" class="btn" @click="submitPageForm(1)">查询</a-button>
                  <a-button type="outline" class="btn" @click="resetPageForm">重置</a-button>
                </a-form-item>
              </div>
              <div class="right">
                <a-button type="primary" class="btn" @click="handleAdd">新增</a-button>
                <a-popconfirm
                  content="确定要删除选中的题目吗？"
                  @ok="handleDelete"
                  position="br"
                >
                  <a-button type="primary" status="danger" class="btn">删除</a-button>
                </a-popconfirm>
              </div>
            </div>
          </a-form>
        </div>
      </div>
      <a-divider>题目管理</a-divider>
      <div class="table-container">
        <a-table
          stripe
          size="medium"
          :scroll="{ x: 1000 }"
          :loading="tableLoading"
          :pagination="false"
          row-key="id"
          :row-selection="rowSelection"
          v-model:selectedKeys="selectedKeys"
          :columns="columns"
          :data="tableData"
        >
          <template #tagsSlot="{ record }">
            <a-tag v-for="tag in record.tags" :key="tag" style="margin-right: 3px" color="arcoblue">
              {{ tag }}
            </a-tag>
          </template>
          <template #optional="{ record }">
            <a-button type="text" status="success" @click="handleEdit(record)">编辑</a-button>
            <a-button type="text" @click="handleViewDetail(record.id)">详情</a-button>
          </template>
        </a-table>
      </div>
      <a-divider />
      <a-pagination
        show-total
        show-jumper
        show-page-size
        size="small"
        :total="total"
        :default-page-size="12"
        :current="pageForm.currentPage"
        :page-size="pageForm.pageSize"
        @change="pageChange"
        @page-size-change="pageSizeChange"
      />
    </div>

    <a-modal
      v-model:visible="detailVisible"
      title="题目详情"
      :footer="null"
      fullscreen
    >
      <a-descriptions :column="1">
        <a-descriptions-item label="题目id">{{ questionDetail.id }}</a-descriptions-item>
        <a-descriptions-item label="题目标题">{{ questionDetail.title }}</a-descriptions-item>
        <a-descriptions-item label="题目内容"><MdViewer :value="questionDetail.content || ''" /></a-descriptions-item>
        <a-descriptions-item label="题目答案"><MdViewer :value="questionDetail.answer || ''" /></a-descriptions-item>
        <a-descriptions-item label="提示信息">{{ questionDetail.prompt}}</a-descriptions-item>
        <a-descriptions-item label="标签列表">
          <a-tag v-for="tag in questionDetail.tags" :key="tag" style="margin-right: 3px" color="arcoblue">
            {{ tag }}
          </a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="提交次数">{{ questionDetail.submitNum }}</a-descriptions-item>
        <a-descriptions-item label="通过次数">{{ questionDetail.acceptedNum }}</a-descriptions-item>
        <a-descriptions-item label="判题配置">
          <pre>{{ questionDetail.judgeConfig }}</pre>
        </a-descriptions-item>
        <a-descriptions-item label="判题用例">
          <pre>{{ questionDetail.judgeCase }}</pre>
        </a-descriptions-item>
        <a-descriptions-item label="创建用户id">{{ questionDetail.userId }}</a-descriptions-item>
        <a-descriptions-item label="创建用户">{{ questionDetail.nickname }}</a-descriptions-item>
        <a-descriptions-item label="创建时间">{{ questionDetail.createTime }}</a-descriptions-item>
        <a-descriptions-item label="更新时间">{{ questionDetail.updateTime }}</a-descriptions-item>
      </a-descriptions>
    </a-modal>
  </div>
</template>

<style scoped>
.card {
  margin-top: 20px;
  background-color: var(--color-bg-1);
  border: 1px solid var(--color-neutral-1);
  padding: 16px;
}

.set-container {
  position: relative;
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
}

.table-container {
  min-height: 60vh;
}

.select-container .btn, .button-container .btn {
  margin-right: 5px;
}

.button-container {
  display: flex;
  justify-content: space-between;
}

.button-container .right {
  position: absolute;
  right: 0;
}
</style>
